package com.fengye.security.jwt.process;

import com.pearadmin.common.tools.servlet.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 已经成功获取用户信息,但是用户的权限不足,不能够访问资源
 */
@Component
@Slf4j
public class JwtAccessDeniedHandler implements AccessDeniedHandler {

    /**
     * 这里不是认证失败
     *
     * 认证成功后,权限不足,不能访问该资源
     *
     * 不能调用 {@link SecurityContextHolder#clearContext()} 来清空认证信息
     *
     * 参考 {@link AccessDeniedHandlerImpl#handle}方法.
     *
     * @param request               {@link HttpServletRequest}
     * @param response              {@link HttpServletResponse}
     * @param accessDeniedException {@link AccessDeniedException}
     * @throws IOException      {@link IOException} 异常
     * @throws ServletException {@link ServletException} 异常
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {
        log.warn("访问 '{}' 权限不足", request.getRequestURI());
        ServletUtil.write("权限不足", HttpStatus.FORBIDDEN);
    }

}